<script setup>
import { ref, defineExpose, defineEmits, nextTick } from 'vue'
import ChannelSelect from './ChannelSelect.vue'
import { Plus } from '@element-plus/icons-vue'

import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {
  artPublishService,
  artGetDetailService,
  artEditService
} from '@/api/article'
import { baseURL } from '@/utils/request'
import axios from 'axios'

const emit = defineEmits(['success'])
const visibleDrawer = ref(false)

const formModel = ref({
  title: '',
  cate_id: '',
  cover_img: '',
  content: '',
  state: ''
})
const rules = {
  title: { required: true, message: '请输入文章标题', trigger: 'blur' },
  cate_id: { required: true, message: '请选择文章分类', trigger: 'change' },
  content: { required: true, message: '请输入文章内容', trigger: 'blur' },
  cover_img: { required: true, message: '请上传文章封面', trigger: 'change' }
}

const imgUrl = ref('')
const onSelectFile = (file) => {
  //   3件事  1处理图片格式，2.存储图片到本地预览，3.赋值给表单
  imgUrl.value = URL.createObjectURL(file.raw)
  formModel.value.cover_img = file.raw
  //   console.log('img', formModel.value.cover_img)
}

// 发布按钮
const onpublish = async (state) => {
  formModel.value.state = state
  const fd = new FormData()
  for (const key in formModel.value) {
    fd.append(key, formModel.value[key])
  }
  //   console.log('formateFormData', fd)
  if (!formModel.value.id) {
    await artPublishService(fd)
    visibleDrawer.value = false
    ElMessage.success('添加成功')
    emit('success', 'add')
  } else {
    // 编辑 1.发请求，2.信息提示 3.通知父组件
    await artEditService(fd)
    visibleDrawer.value = false
    ElMessage.success('编辑成功')
    emit('success', 'edit')
  }
}
const defaultForm = {
  title: '',
  cate_id: '',
  cover_img: '',
  content: '',
  state: ''
}
const editorRef = ref()
const open = async (row) => {
  visibleDrawer.value = true
  if (row.id) {
    // 发请求 - 获取文章详情
    const res = await artGetDetailService(row.id)
    // console.log(res)
    formModel.value = res.data.data
    // 1.图片要正常展示需要拼接baseUrl
    imgUrl.value = baseURL + formModel.value.cover_img
    //2.再把本地和表单里的图片，转换成file格式 - 接口需要这个格式
    formModel.value.cover_img = await imageUrlToFile(
      imgUrl.value,
      formModel.value.cover_img
    )
    // 重置内容为编辑项的内容
    nextTick(() => {
      editorRef.value.setHTML(formModel.value.content)
    })
  } else {
    //新增- 清空所有内容
    formModel.value = { ...defaultForm }
    nextTick(() => {
      imgUrl.value = ''
      editorRef.value = ''
    })
  }
}
defineExpose({ open })

// 将网络图片地址转换为File对象
async function imageUrlToFile(url, fileName) {
  try {
    // 第一步：使用axios获取网络图片数据
    const response = await axios.get(url, { responseType: 'arraybuffer' })
    const imageData = response.data

    // 第二步：将图片数据转换为Blob对象
    const blob = new Blob([imageData], {
      type: response.headers['content-type']
    })

    // 第三步：创建一个新的File对象
    const file = new File([blob], fileName, { type: blob.type })

    return file
  } catch (error) {
    console.error('将图片转换为File对象时发生错误:', error)
    throw error
  }
}
</script>

<template>
  <el-drawer
    v-model="visibleDrawer"
    title="发布文章"
    direction="rtl"
    size="50%"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      label-width="100px"
      :rules="rules"
    >
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="formModel.title"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="cate_id">
        <ChannelSelect v-model="formModel.cate_id"></ChannelSelect>
      </el-form-item>
      <el-form-item label="文章封面" prop="cover_img">
        <!-- auto-upload 默认true 是否自动上传文件，我们是本地预览，确定发布后才上传 -->
        <!--show-file-list 默认true 是否显示已上传的文件 -->
        <!-- on-change 钩子函数 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用-->
        <el-upload
          class="avatar-uploader"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onSelectFile"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div class="editor">
          <quill-editor
            ref="editorRef"
            theme="snow"
            v-model:content="formModel.content"
            contentType="html"
          >
          </quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onpublish('已发布')">发布</el-button>
        <el-button type="info" @click="onpublish('草稿')">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
